package com.jaws.demo.configuration;

import com.alibaba.druid.pool.DruidDataSource;
import com.jaws.demo.schedule.quartz.DynamicSchedulerFactory;
import com.jaws.demo.schedule.quartz.QuartzJobFactory;
import lombok.extern.slf4j.Slf4j;
import org.quartz.Scheduler;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;

import javax.sql.DataSource;


/**
 * 配置Quartz
 *
 * @author liangqm
 * @date 2018-04-24 9:20:18
 * @since v1.0.1
 */
@Configuration
@EnableConfigurationProperties(QuartzConfigProperties.class)
@Slf4j
public class QuartzConfiguration {

	@Value("${scheduler.auto.startup}")
	private boolean autoStartup;

	@Bean
	@ConfigurationProperties(prefix = "spring.datasource.quartz")
	public DataSource quartzDataSource() {
		DruidDataSource quartzDataSource = new DruidDataSource();
		return quartzDataSource;
	}


	@Bean
	public SchedulerFactoryBean schedulerFactory(@Qualifier("quartzDataSource") DataSource quartzDataSource , QuartzJobFactory quartzJobFactory) {
		SchedulerFactoryBean schedulerFactory = new SchedulerFactoryBean();
		schedulerFactory.setDataSource(quartzDataSource);
		schedulerFactory.setAutoStartup(autoStartup);
		schedulerFactory.setJobFactory(quartzJobFactory);
		//Quartz 配置
//		schedulerFactory.setQuartzProperties();
		return schedulerFactory;
	}

	@Bean
	public QuartzJobFactory quartzJobFactory() {
		return new QuartzJobFactory();
	}

	@Bean
	public DynamicSchedulerFactory dynamicSchedulerFactory(Scheduler schedulerFactory) {
		DynamicSchedulerFactory dynamicSchedulerFactory = new DynamicSchedulerFactory();
		dynamicSchedulerFactory.setScheduler(schedulerFactory);
		return dynamicSchedulerFactory;
	}


//	/**
//	 * 读取配置文件
//	 *
//	 * @return
//	 * @throws IOException
//	 * @author huqingjia
//	 * @date 2018-04-17 11:58:24
//	 * @since 1.0.0
//	 */
//	@Bean
//	public Properties quartzProperties() throws IOException {
//		PropertiesFactoryBean propertiesFactoryBean = new PropertiesFactoryBean();
//		propertiesFactoryBean.setLocation(new ClassPathResource("/quartz.properties"));
//		// 在quartz.properties中的属性被读取并注入后再初始化对象
//		propertiesFactoryBean.afterPropertiesSet();
//		Properties props = propertiesFactoryBean.getObject();
//		log.info("quartzProperties = {}", props);
//		return props;
//	}

}
